/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cnguifang.feigewallet.ui;

import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.cnguifang.feigewallet.DemoHelper;
import com.cnguifang.feigewallet.R;
import com.cnguifang.feigewallet.data.result.SmsCode;
import com.cnguifang.feigewallet.network.AppNetworkUtils;
import com.cnguifang.feigewallet.network.NetworkResultUtils;
import com.cnguifang.feigewallet.utils.AccountValidatorUtil;
import com.hyphenate.exceptions.HyphenateException;
import com.mathum.baseapp.config.Config;
import com.mathum.baseapp.data.BaseData;
import com.mathum.baseapp.network.NetworkCallback;
import com.mathum.baseapp.network.NetworkUtils;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * register screen
 */
public class RegisterActivity extends BaseActivity {
    private EditText userNameEditText;
    private EditText passwordEditText;
    private EditText confirmPwdEditText;
    private TextView tvCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.em_activity_register);
        userNameEditText = (EditText) findViewById(R.id.username);
        passwordEditText = (EditText) findViewById(R.id.password);
        confirmPwdEditText = (EditText) findViewById(R.id.sms_code);
        tvCount = (TextView) findViewById(R.id.tv_count);
        tvCount.setOnClickListener(view -> {
            if (TextUtils.isEmpty(userNameEditText.getText().toString())) {
                Toast.makeText(RegisterActivity.this, "手机号码不能为空", Toast.LENGTH_LONG).show();
                return;
            }
            if (TextUtils.isEmpty(passwordEditText.getText().toString())) {
                Toast.makeText(RegisterActivity.this, "密码不能为空", Toast.LENGTH_LONG).show();
                return;
            }
            if (!AccountValidatorUtil.isMobile(userNameEditText.getText().toString())) {
                Toast.makeText(RegisterActivity.this, "手机格式错误", Toast.LENGTH_LONG).show();
                return;
            }
            tvCount.setText("已发送");
            NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().fetchSmsCode(userNameEditText.getText().toString()),
                    new NetworkCallback<SmsCode>() {
                        @Override
                        public void onSuccess(SmsCode baseData) {
                            confirmPwdEditText.setText(baseData.getCodemsg().trim());
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            Toast.makeText(RegisterActivity.this, "网络异常", Toast.LENGTH_LONG).show();
                        }
                    });
        });
    }

    public void register(View view) {
        final String username = userNameEditText.getText().toString().trim();
        final String pwd = passwordEditText.getText().toString().trim();
        String confirm_pwd = confirmPwdEditText.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, getResources().getString(R.string.User_name_cannot_be_empty), Toast.LENGTH_SHORT).show();
            userNameEditText.requestFocus();
            return;
        } else if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, getResources().getString(R.string.Password_cannot_be_empty), Toast.LENGTH_SHORT).show();
            passwordEditText.requestFocus();
            return;
        } else if (TextUtils.isEmpty(confirm_pwd)) {
            Toast.makeText(this, "验证码不能为空!", Toast.LENGTH_SHORT).show();
            confirmPwdEditText.requestFocus();
            return;
        }

        if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
            final ProgressDialog pd = new ProgressDialog(this);
            pd.setMessage(getResources().getString(R.string.Is_the_registered));
            pd.show();

            //注册
            NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().register(username, pwd, confirm_pwd),
                    new NetworkCallback<BaseData>() {
                        @Override
                        public void onSuccess(BaseData baseData) {
                            if (!NetworkResultUtils.isSuccess(baseData)) {
                                pd.dismiss();
                                Toast.makeText(RegisterActivity.this, baseData.getInfo(), Toast.LENGTH_LONG).show();
                                return;
                            }
                            if (!RegisterActivity.this.isFinishing())
                                pd.dismiss();
                            // save current user
                            DemoHelper.getInstance().setCurrentUserName(username);
                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), Toast.LENGTH_SHORT).show();
//                            Intent intent = new Intent(RegisterActivity.this,UserInfoActivity.class);
//                            startActivity(intent);
                            finish();
//                            new Thread(new Runnable() {
//                                public void run() {
//                                    try {
//                                        // call method in SDK
//                                        EMClient.getInstance().createAccount(username, pwd);
//                                        runOnUiThread(new Runnable() {
//                                            public void run() {
//                                                if (!RegisterActivity.this.isFinishing())
//                                                    pd.dismiss();
//                                                // save current user
//                                                DemoHelper.getInstance().setCurrentUserName(username);
//                                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), Toast.LENGTH_SHORT).show();
//                                                finish();
//                                            }
//                                        });
//                                    } catch (final HyphenateException e) {
//                                        runOnUiThread(new Runnable() {
//                                            public void run() {
//                                                if (!RegisterActivity.this.isFinishing())
//                                                    pd.dismiss();
//                                                int errorCode = e.getErrorCode();
//                                                if (errorCode == EMError.NETWORK_ERROR) {
//                                                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
//                                                } else if (errorCode == EMError.USER_ALREADY_EXIST) {
//                                                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
//                                                } else if (errorCode == EMError.USER_AUTHENTICATION_FAILED) {
//                                                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
//                                                } else if (errorCode == EMError.USER_ILLEGAL_ARGUMENT) {
//                                                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name), Toast.LENGTH_SHORT).show();
//                                                } else if (errorCode == EMError.EXCEED_SERVICE_LIMIT) {
//                                                    Toast.makeText(RegisterActivity.this, getResources().getString(R.string.register_exceed_service_limit), Toast.LENGTH_SHORT).show();
//                                                } else {
//                                                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed), Toast.LENGTH_SHORT).show();
//                                                }
//                                            }
//                                        });
//                                    }
//                                }
//                            }).start();
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            pd.dismiss();
                            Toast.makeText(RegisterActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });


        }
    }

    public void back(View view) {
        finish();
    }

}
